package com.nescafe.nescafepromo.model;

import java.io.UnsupportedEncodingException;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.xml.bind.DatatypeConverter;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class SignedRequest {

	private static final Logger log = Logger.getLogger(SignedRequest.class.getName());

	private String code = null;
	private String userID = null;
	private String oauthToken = null;

	private String encodedData;
	private JsonObject data;

	public SignedRequest(String value) {
		try {
			value = padBase64(value);
			String[] splits = value.split(Pattern.quote("."));
			log.info("VALUE = " + value);
			encodedData = splits[1];
			data = (JsonObject) new JsonParser().parse(base64UrlDecode(encodedData));
			userID = data.has("user_id") ? data.get("user_id").getAsString() : null;
			oauthToken = data.has("oauth_token") ? data.get("oauth_token").getAsString() : null;
		} catch (Exception e) {

		}

	}

	public String getCode() {
		return code;
	}

	public String getUserID() {
		return userID;
	}

	public String getOauthToken() {
		return oauthToken;
	}

	public boolean isAuthorized() {
		return userID != null && oauthToken != null;
	}

	public JsonObject getData() {
		return data;
	}

	private String base64UrlDecode(String encoded) throws UnsupportedEncodingException {
		// Base64 base64 = new Base64(true); // URL-safe mode
		byte[] decodedPayload = DatatypeConverter.parseBase64Binary(encoded);
		return new String(decodedPayload, "UTF-8");
	}

	private String padBase64(String b64) {
		String padding = "";
		switch (b64.length() % 4) {
			case 0 :
				break;
			case 1 :
				padding = "===";
				break;
			case 2 :
				padding = "==";
				break;
			default :
				padding = "=";
		}
		return b64 + padding;

	}
}
